import { defineComponent, PropType, VNode, watch } from 'vue';
import { useController } from '@ibiz-template/vue3-util';
import { IDEFormMDCtrl } from '@ibiz/model-core';
import { FormMDCtrlController } from './form-mdctrl.controller';

export const FormMDCtrl = defineComponent({
  name: 'IBizFormMDCtrl',
  props: {
    modelData: {
      type: Object as PropType<IDEFormMDCtrl>,
      required: true,
    },
    controller: {
      type: FormMDCtrlController,
      required: true,
    },
  },
  setup(props) {
    useController(props.controller);

    const c = props.controller;

    watch(
      () => c.form.state.isLoaded,
      (n, o) => {
        if (n !== o && n === true) {
          c.loadData();
        }
      },
    );

    const renderContentRepeater = (): VNode | undefined => {
      switch (c.model.detailStyle) {
        case 'STYLE2':
          return (
            <iBizFormMDCtrlRepeaterGrid
              controller={c.mdCtrlContentController}
            />
          );
        case 'STYLE3':
          return (
            <iBizFormMDCtrlRepeaterFormOne
              controller={c.mdCtrlContentController}
            />
          );
        default:
          return (
            <iBizFormMDCtrlRepeaterForm
              controller={c.mdCtrlContentController}
            />
          );
      }
    };

    return { c, renderContentRepeater };
  },
  render() {
    const renderContentByType = (): VNode | undefined => {
      let content;
      const { model } = this.c;
      switch (model?.contentType) {
        case 'FORM':
          content = (
            <iBizFormMDCtrlForm controller={this.c.mdCtrlContentController} />
          );
          break;
        case 'GRID':
          content = (
            <iBizFormMDCtrlGrid controller={this.c.mdCtrlContentController} />
          );
          break;
        case 'LIST':
          content = (
            <iBizFormMDCtrlList controller={this.c.mdCtrlContentController} />
          );
          break;
        case 'DATAVIEW':
          content = (
            <iBizFormMDCtrlDataView
              controller={this.c.mdCtrlContentController}
            />
          );
          break;
        case 'REPEATER':
          content = this.renderContentRepeater();
          break;

        default:
          break;
      }
      return content;
    };
    return renderContentByType();
  },
});

export default FormMDCtrl;
